/*********************************************************************************
 *      Copyright:  (C) 2021 ljl
 *                  All rights reserved.
 *
 *       Filename:  ds38b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2021年12月14日)
 *         Author:  Li Jiale <244871365@qq.com>
 *      ChangeLog:  1, Release initial version on "2021年12月14日 21时48分12秒"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <errno.h>

int ds18b20_get_temperature(float *temp)
{
    int                 fd = -1;
    DIR                 *dirp = NULL;
    struct dirent       *direntp = NULL;
    char                w1_path[64] = "/sys/bus/w1/devices/";
    char                chip_sn[32];
    char                ds18b20_path[128];
    int                 found=0;
    char                buf[128];
    char                *ptr = NULL;
    float               temperature;    

    dirp = opendir(w1_path);
    if(!dirp)
    {
        //syslog(LOG_WARNING,"open dirent /sys/bus/w1/devices/ failure\n");
        printf("open dirent /sys/bus/w1/devices/ failure\n");
        return -1;
    }

    while(NULL!=(direntp = readdir(dirp)))
    {
        if(strstr(direntp->d_name,"28-"))
        {
            strncpy(chip_sn,direntp->d_name,sizeof(chip_sn));
            found = 1;
        }
    }

    if(!found)
    {
        //syslog(LOG_WARNING,"can not find ds18b20 chipset\n");
        printf("open dirent /sys/bus/w1/devices/ failure\n");
        return -2;
    }
        
    closedir(dirp);

    snprintf(ds18b20_path,sizeof(ds18b20_path),"%s/%s/w1_slave",w1_path,chip_sn);

    fd = open(ds18b20_path,O_RDONLY);
    if(fd < 0)
    {
        //syslog(LOG_WARNING,"open failure w1_slave failure:%s\n",strerror(errno));
        printf("open failure w1_slave failure:%s\n",strerror(errno));
        return -3;
    }

    memset(buf,0,sizeof(buf));

    if( read(fd,buf,sizeof(buf)) < 0)
    {
        //syslog(LOG_WARNING,"read w1_slave faiure:%s\n",strerror(errno));
        printf("read w1_slave faiure:%s\n",strerror(errno));
        return -4;
    }

    ptr = strstr(buf,"t=");
    if( !ptr )
    {
        //syslog(LOG_WARNING,"w1_slave can no find t=\n");
        printf("w1_slave can no find t=\n");
        return -5;
    }
    ptr += 2;

    *temp = atof(ptr)/1000;

    close(fd);
    return 0;
}
